-----------------------------------------------------------------------------------------
-- filename : player.lua
-- description : player logic and atributte must be here
-----------------------------------------------------------------------------------------

-- Load needed libraries/scripts
local player = {}
local player_mt = {__index = player}
local pion = require "pion"
local layer = require "layer"
local storyboard = require "storyboard"
local json = require "json"
local fontfactory = require "fontfactory"

-- loacal variables
player.n = 0
players = {}
nMax = 5

function player.new(name) 

	if(name == nil) then
		name = "dummy"
	end

	-- load description of player based on name character json file
	local playerJson = loadJSON("assets/chara/"..name..".json")

	local newPlayer = {
		id = player.n,
		pions = {},
		enable = true,
		nDiceTurn = 0,
		score = 0,
		scoreText = nil
	}

	player.n = player.n + 1
	if(newPlayer.id == 0) then
		
		local player_image = display.newImageRect( "assets/chara/"..playerJson.image.image_path,playerJson.image.width, playerJson.image.height, true )
		player_image:setReferencePoint(display.TopLeftReferencePoint)
		player_image.x = -140
		player_image.y = 20
		player_image:addEventListener("touch", newPlayer)
		player_image:setReferencePoint(display.CenterReferencePoint)

		local player_image_back = display.newImageRect( "assets/chara/"..playerJson.image.image_bright,playerJson.image.width, playerJson.image.height, true )
		player_image_back:setReferencePoint(display.TopLeftReferencePoint)
		player_image_back.x = -140
		player_image_back.y = 20
		player_image_back:addEventListener("touch", newPlayer)
		player_image_back:setReferencePoint(display.CenterReferencePoint)
		player_image_back:scale(1.1,1.1)


		local image = display.newImageRect( "assets/hud_bar.png", 144, 66, true )
		image:setReferencePoint(display.TopLeftReferencePoint)
		image.x = 0
		image.y = 0 + display.screenOriginY 
		
		local switch = display.newImageRect( "assets/switch_on.png", 45, 59, isFullResolution )
		switch:setReferencePoint(display.TopLeftReferencePoint)
		switch.x = 17
		switch.y = 250

		local switch_off = display.newImageRect( "assets/switch_off.png", 45, 59, isFullResolution )
		switch_off:setReferencePoint(display.TopLeftReferencePoint)
		switch_off.x = 17
		switch_off.y = 250

		--newPlayer:setReferencePoint(display.TopRightReferencePoint)
		newPlayer.scoreText = display.newText("0",0,0,fontfactory.dimitry,16)
		newPlayer.scoreText.x = image.width - 25
		newPlayer.scoreText.y = 15 +  display.screenOriginY 

		layer.insertImage(layer.BACKGROUND,player_image_back)
		layer.insertImage(layer.BACKGROUND,player_image)
		layer.insertImage(layer.HUD,image)
		layer.insertImage(layer.HUD,switch)
		layer.insertImage(layer.HUD,switch_off)
		newPlayer.image = player_image
		newPlayer.effect = player_image_back
		newPlayer.switch_on = switch;
		newPlayer.switch_off = switch_off;

	elseif (newPlayer.id == 1) then
		local player_image = display.newImageRect( "assets/chara/"..playerJson.image.image_path,playerJson.image.width, playerJson.image.height, true )
		player_image:setReferencePoint(display.TopRightReferencePoint)
		player_image.y = 20
		player_image.x = 480+140
		player_image:addEventListener("touch", newPlayer)
		player_image:setReferencePoint(display.CenterReferencePoint)
		player_image.xScale = -1

		local player_image_back = display.newImageRect( "assets/chara/"..playerJson.image.image_bright,playerJson.image.width, playerJson.image.height, true )
		player_image_back:setReferencePoint(display.TopRightReferencePoint)
		player_image_back.x = 480+140
		player_image_back.y = 20
		player_image_back:addEventListener("touch", newPlayer)
		player_image_back:setReferencePoint(display.CenterReferencePoint)
		player_image_back.xScale = -1
		player_image_back:scale(1.1,1.1)
		

		local image = display.newImageRect( "assets/hud_bar.png", 144, 66, true )
		image:setReferencePoint(display.TopLeftReferencePoint) 
		image.xScale = -1
		image.x = 480
		image.y = 0 + display.screenOriginY 

		local switch = display.newImageRect( "assets/switch_on.png", 45, 59, isFullResolution )
		switch:setReferencePoint(display.TopLeftReferencePoint)
		switch.xScale = -1
		switch.y = 250
		switch.x = 480-17

		local switch_off = display.newImageRect( "assets/switch_off.png", 45, 59, isFullResolution )
		switch_off:setReferencePoint(display.TopLeftReferencePoint)
		switch_off.xScale = -1
		switch_off.y = 250
		switch_off.x = 480-17

		--newPlayer:setReferencePoint(display.TopLeftReferencePoint)
		newPlayer.scoreText = display.newText("0",0,0,fontfactory.dimitry,16)
		newPlayer.scoreText.x = 480 - image.width + 25
		newPlayer.scoreText.y = 15 +  display.screenOriginY 
		
		layer.insertImage(layer.BACKGROUND,player_image_back)
		layer.insertImage(layer.BACKGROUND,player_image)
		layer.insertImage(layer.HUD,image)
		layer.insertImage(layer.HUD,switch)
		layer.insertImage(layer.HUD,switch_off)
		newPlayer.image = player_image
		newPlayer.effect = player_image_back
		newPlayer.switch_on = switch;
		newPlayer.switch_off = switch_off;
	end

	

	layer.insertImage(layer.HUD, newPlayer.scoreText)

	setmetatable(newPlayer,player_mt)

	table.insert(players,newPlayer)

	return newPlayer
end

function player:touch(event)
	if (event.phase == "began") then
		local options = 
		{
			effect = "slideRight",
    		time = 300,
			params = 
			{
				callback = self,
				playerid = self.id,
				character = "assets/chara/character_gameplay_dummy.png"
			}
		}

		if(self.id == 1) then
			options.effect = "slideLeft"
		end
		
		storyboard.showOverlay("pause_scene",options)
	end
	return true
end

function player:addPion(_pion)
	table.insert(self.pions,_pion)
end

function player:removePion(_pion)
	local idx = -1
	for i=1,table.getn(self.pions) do
		if(self.pions[i] == _pion) then
			idx = i
			break
		end
	end
	if(idx >= 0) then
		table.remove(self.pions,idx)
	end
end

function player:createPion(_board,row,col)
	local newPion = pion.new(self,_board,row,col)
	self:addPion(newPion)
	return newPion
end

function player:isFinishTurn()
	for i=1,table.getn(self.pions) do
		if(self.pions[i].enable) then
			return false
		end
	end

	return true
end

function player:remainPions()
	local count = 0
	for i=1,table.getn(self.pions) do
		if(self.pions[i].enable) then
			count = count + 1
		end
	end

	return count
end

function player:startTurn()
	self.image:setFillColor(255, 255, 255)
	self.effect.alpha = 150
	self.image.xScale = 1.1
	self.image.yScale = 1.1
	if(self.id == 1) then 
		self.image.xScale = self.image.xScale*-1
	end
	for i=1,table.getn(self.pions) do
		self.pions[i]:setEnable(true)
	end

	-- switch on
	self.switch_on.isVisible = true;
	self.switch_off.isVisible = false;
end

function player:endTurn()
	self.image:setFillColor(100, 100, 100)
	self.image.xScale = 0.8
	self.image.yScale = 0.8
	self.effect.alpha = 0
	if(self.id == 1) then 
		self.image.xScale = self.image.xScale*-1
	end
	for i=1,table.getn(self.pions) do
		self.pions[i].enable = false
	end

	-- switch off
	self.switch_on.isVisible = false;
	self.switch_off.isVisible = true;
end

function player:nextTurn(cPlayer)
	for i=1,table.getn(players) do
		if (players[i].id == cPlayer.id) then
			print("AAAAAA")
			cPlayer:endTurn()
			if(i+1 == table.getn(players)+1) then
				players[(1)]:startTurn()
			else
				players[(i+1)]:startTurn()
			end
			break
		end
	end
end

function player:addScore(difScore)
	self.score = self.score + difScore
	self.scoreText.text = ""..self.score
end

function player:isDiceFull() 
	return table.getn(self.pions) == nMax
end

function loadJSON( filename )
    -- set default base dir if none specified
    local base = system.ResourceDirectory
    -- create a file path for corona i/o
    local path = system.pathForFile( filename, base )
    -- will hold contents of file
    local contents
    -- io.open opens a file at path. returns nil if no file found

    local file = io.open( path, "r" )
    if file then
        -- read all contents of file into a string
        contents = file:read( "*a" )
        io.close( file )    -- close the file after using it
        --return decoded json string
        return json.decode( contents )
    else
        --or return nil if file didn't ex
        return nil
    end
end

return player